package com.example.demo.config;

import cn.hutool.core.util.StrUtil;
import com.example.demo.util.BodyReaderHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zhangfc
 * @date 2022/1/10 17:01
 */
@Component
@Order(2)
@WebFilter(filterName = "myCorsFilter", urlPatterns = "/*")
@Slf4j
public class MyCorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
        String method = requestWrapper.getMethod();
        String requestURI = requestWrapper.getRequestURI();
        if (StrUtil.containsAny(requestURI, "/css/", "/fonts/", "/js/", "/img/", "favicon.ico","/druid/","/webjars/","doc")) {
            filterChain.doFilter(requestWrapper, servletResponse);
            return;
        }
        String body = IOUtils.toString(requestWrapper.getReader());
        log.info("请求url=:{},method=:{},body=:{}", requestURI, method, body);

        filterChain.doFilter(requestWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
